<?php
namespace app\admin\controller;

use think\Db;
use think\facade\Session;

class Content extends Base
{
	public function content()
	{
        if ($this->request->isPost() && $this->request->isAjax()) {
            // 查询
            $map = [];

            $column_id = $this->request->param('column_id/d', 0);
            if ($column_id) {
                $map[] = ['column_id', 'in', column_childrens_id($column_id)];
            }

            $title = $this->request->param('title/s', '');
            if ('' !== $title) {
                $map[] = ['title', 'like', '%'.$title.'%'];
            }

            // 分页
            $page = $this->request->param('page/d', 0);
            $limit = $this->request->param('limit/d', 0);
            $count = Db::table('content')->where($map)->count();
            
            $data = Db::table('content')->where($map)->limit($limit * ($page - 1), $limit)->order('update_time desc')->select();

            if ($data) {
                $column = Db::table('column')->column('name', 'id');
                foreach ($data as &$v) {
                    $v['column_name'] = array_key_exists($v['column_id'], $column) ? $column[$v['column_id']] : '';
                    $v['update_time'] = $v['update_time'] ? date('Y-m-d H:i:s', $v['update_time']) : '';
                }
            }
            
            // 返回数据
            $res = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $data,
            ];

            return json($res);
        }

        $this->assign('editor', 'jodit');
        $this->assign('column', column_list('id,pid,name,type'));

		return $this->fetch();
	}

    public function contentForm()
    {
        $id = $this->request->param('id/d', 0);
        if ($id) {
            $content = Db::table('content')->where('id', $id)->find();
            if (!$content) {
                $this->error('内容不存在');
            }
            $this->assign('content', $content);

            $content_data = Db::table('content_data')->where('content_id', $id)->value('content');
            if (!$content_data) {
                $content_data = '';
            }
            $this->assign('content_data', $content_data);
            
        } else {
            $column_id = $this->request->param('column_id/d', 0);
            $column = Db::table('column')->where('id', $column_id)->find();
            // 栏目是否存在，是否为内容类型，是否有子栏目
            if ($column && $column['type'] == 0 && count(column_childrens_id($column['id'])) === 1) {
                $this->assign('content', ['column_id' => $column_id]);
            }
        }

        $this->assign('column', column_list('id,pid,name,type'));

		return $this->fetch();
    }

    public function contentSave()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/d', 0);
            $data = [
                'column_id'     => $this->request->param('column_id/d', 0),
                'title'         => trim($this->request->param('title/s', '')),
                'top'           => $this->request->param('top/s', 0) === 'on' ? 1 : 0,
                'recommend'     => $this->request->param('recommend/s', 0) === 'on' ? 1 : 0,
                'pic'           => trim($this->request->param('pic/s', '')),
                'url'           => trim($this->request->param('url/s', '')),
                'publish'       => $this->request->param('publish/d', 0),
                'author'        => trim($this->request->param('author/s', '')),
                'source'        => trim($this->request->param('source/s', '')),
                'clicks'        => $this->request->param('clicks/d', 0),
                'sort'          => $this->request->param('sort/d', 0),
                'seotitle'      => $this->request->param('seotitle/s', ''),
                'keywords'      => $this->request->param('keywords/s', ''),
                'description'   => $this->request->param('description/s', ''),
                'update_user'   => Session::get('user.name'),
                'update_time'   => empty($this->request->param('update_time/s', '')) ? 0 : strtotime($this->request->param('update_time/s', '')),
            ];

            // 栏目检测
            $column_type = Db::table('column')->where('id', $data['column_id'])->value('type');
            if (!$column_type && $column_type) {
                $this->result('', 1, '栏目错误');
            }

            // 添加编辑状态检测
            if ($id) {
                if (!Db::table('content')->where('id', $id)->update($data)) {
                    $this->result('', 1, '编辑内容失败');
                }

                $content_id = $id;
            } else {
                $data['add_user'] = Session::get('user.name');
                $data['add_time'] = time();
                $data['user_id'] = Session::get('user.id');

                $content_id = Db::table('content')->insertGetId($data);
                if (!$content_id) {
                    $this->result('', 1, '添加内容失败');
                }
            }

            // 更新内容数据表
            if (Db::table('content_data')->where('content_id', $content_id)->count()) {
                Db::table('content_data')->where('content_id', $content_id)->update(['content' => $this->request->param('editorValue/s', '')]);
            } else {
                Db::table('content_data')->insert(['content_id' => $content_id, 'content' => $this->request->param('editorValue/s', '')]);
            }

            $this->result('', 0, '保存成功');
        }
    }

    public function contentDels()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $ids = explode(',', $this->request->param('ids/s', ''));
            array_walk($ids, function(&$v) { $v = intval($v); });

            if (!Db::table('content')->where('id', 'in', $ids)->delete()) {
                $this->result('', 1, '删除失败');
            }

            Db::table('content_data')->where('content_id', 'in', $ids)->delete();

            $this->result('', 0, '删除成功');
        }
    }

    public function contentSort()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            if (!Db::table('content')->where('id', $this->request->param('id/d', 0))->setField('sort', $this->request->param('sort/d', 0))) {
                $this->result('', 1, '排序失败');
            }

            $this->result('', 0, '排序成功');
        } 
    }

    public function contentUpdate() {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $key = trim($this->request->param('key/s', ''));
            $value = trim($this->request->param('value/s', ''));

            $ids = explode(',', $this->request->param('ids/s', ''));
            array_walk($ids, function(&$v) { $v = intval($v); });

            if (!Db::table('content')->where('id', 'in', $ids)->setField($key, $value)) {
                $this->result('', 1, '更新失败');
            }

            $this->result('', 0, '更新成功');
        }
    }

    public function page()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/d', 0);

            if (!Db::table('column')->where('id', $id)->count()) {
                $this->result('', 1, '栏目不存在');
            }

            $content = Db::table('content_data')->where('column_id', $id)->value('content');
            if (!$content) {
                if (!Db::table('content_data')->insert(['column_id' => $id, 'content' => ''])) {
                    $this->result('', 1, '单页栏目内容添加失败');
                }
                $content = '';
            }

            $this->result($content, 0, '加载成功');
        }
    }

    public function pageSave()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/d', 0);
            $content = $this->request->param('editorValue/s', '');

            if (!Db::table('column')->where('id', $id)->count()) {
                $this->result('', 1, '栏目不存在');
            }

            if (!Db::table('content_data')->where('column_id', $id)->setField('content', $content)) {
                $this->result('', 1, '保存失败');
            }

            $this->result('', 0, '保存成功');
        }
    }

    public function columnTree()
    {
        return json(column_tree('id,pid,name as title,type,url'));
    }
}
